/**
 * @filename:WorkSettingController Feb 22, 2024
 * @project Wonder Vue Admin Api  1.1.0
 * Copyright(c) 2020 Wonder Co. Ltd. 
 * All right reserved. 
 */
package com.wonder.app.controller;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Date;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.vtuzx.core.bean.dto.VtuzxMap;
import com.wonder.admin.domain.SysAdmin;
import com.wonder.admin.service.SysAdminService;
import com.wonder.app.domain.Testwave;
import com.wonder.app.domain.WorkSetting;
import com.wonder.app.domain.Worktest;
import com.wonder.app.domain.Workvs;
import com.wonder.app.mapper.WorkSettingDao;
import com.wonder.app.mapper.WorktestDao;
import com.wonder.app.mapper.WorkvsDao;
import com.wonder.app.service.WorkSettingService;
import com.wonder.app.request.WorkSettingRequest;
import com.wonder.app.service.WorktestService;
import com.wonder.app.service.WorkvsService;
import com.wonder.config.MqttProviderConfig;
import com.wonder.framework.authorization.CheckAdminToken;
import jnr.ffi.annotations.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.wonder.common.common.AjaxMap;
import com.wonder.common.common.AjaxResult;
import com.wonder.common.common.CommonPage;
import com.wonder.common.utils.MessageUtils;
import com.wonder.common.utils.StringUtils;
import com.alibaba.fastjson.JSON;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiImplicitParam;

import javax.servlet.http.HttpServletRequest;

/**
 * 
 * <p>说明： 工单设置API接口层</P>
 * @version: 1.1.0
 * @author: Wonder
 * @time    Feb 22, 2024
 *
 */
@Api(tags = "工单设置")
@RestController
@RequestMapping("/app/WorkSetting")
public class WorkSettingController {
	
	@Autowired
	private WorkSettingService workSettingService;
	@Autowired
	private WorkSettingDao workSettingDao;
	@Autowired
	private CheckAdminToken checkAdminToken;
	@Autowired
	private SysAdminService adminService;
	@Autowired
	private WorkvsService workvsService;
	@Autowired
	private WorkvsDao workvsDao;
	@Autowired
	private WorktestService worktestService;
	@Autowired
	private MqttProviderConfig providerConfig;

	@ApiOperation(value = "工单设置列表")
	@RequestMapping(value = "/index", method = RequestMethod.POST)
	public Map<String,Object> index(@RequestBody WorkSettingRequest workSettingRequest) {
		Page<WorkSetting> page = new Page<WorkSetting>(workSettingRequest.getPage(), workSettingRequest.getLimit());
		IPage<WorkSetting> list = workSettingService.selectList(workSettingRequest, page);
		
		Map<String,Object> retMap=new HashMap<>();
		retMap.put("data",CommonPage.restPage(list));
		
  
		return AjaxMap.success(retMap);
	}
	
	/**
	 * @explain 修改排序开关
	 * @param   entity
	 * @return  Boolean
	 * @author  Wonder
	 */
	@PostMapping("/updateExt")
	@ApiOperation(value = "修改排序开关", notes = "作者：Wonder")
	public AjaxResult<WorkSetting> updateExt(@RequestBody WorkSetting entity){
		if (null!=entity) {
			boolean rsg = workSettingService.updateById(entity);
			if (rsg) {
				  return AjaxResult.success("system.updateSuccess");
			  }else {
				  return AjaxResult.failed("system.updateFailed");
			  }
		}else {
			return AjaxResult.failed("system.parameterError");
		}
	}

	/**
	 * 创建工单
	 * @param request
	 * @param map
	 * @return
	 * @throws Exception
	 */
		@PostMapping("/add")
		@ApiOperation(value = "添加", notes = "作者：Wonder")
		public AjaxResult<Boolean> add(HttpServletRequest request, @RequestBody Map<String,Object> map)throws Exception {

			//获取token
			String token = checkAdminToken.getTokenFormRequest(request);
			SysAdmin user = adminService.getAdminByToken(token);
			String userName = user.getName();
			if(map==null)return AjaxResult.failed("system.parameterError");
			List<Map<String,Object>> datavsList = (List<Map<String,Object>>)map.get("datavslist");
			List<Map<String,Object>> datatestList = (List<Map<String, Object>>)map.get("datatestlist");
			Map<String,Object> header = (Map<String, Object>) map.get("header");
			boolean isSuccess = workSettingService.saveworkorder(userName,header,datavsList,datatestList);
			return AjaxResult.success(isSuccess);

		}
	
	/**
	 * @explain 查询对象  <swagger GET请求>
	 * @param   map 对象参数：id
	 * @return  JsonResult
	 * @author  Wonder
	 */
	@PostMapping("/getUpdateInfo")
	@ApiOperation(value = "获取工单设置对象", notes = "作者：Wonder")
	public AjaxResult<WorkSetting> getUpdateInfo(@RequestBody Map<String,Object> map){
	    if(map==null) return AjaxResult.failed("system.parameterError");
		Long id=Long.parseLong(map.get("id").toString());		
		 WorkSetting workSetting=workSettingService.getById(id);
		
		if (null!=workSetting ) {
			 return AjaxResult.success(workSetting);
		}else {
			 return AjaxResult.failed("system.parameterError");
		}
		
	}

	/**
	 * 工单修改
	 * @param request
	 * @param map
	 * @return
	 * @throws Exception
	 */
	@PostMapping("/update")
	@ApiOperation(value = "修改", notes = "作者：Wonder")
	public AjaxResult<Boolean> update(HttpServletRequest request, @RequestBody Map<String,Object> map)throws Exception {

		//获取token
		String token = checkAdminToken.getTokenFormRequest(request);
		SysAdmin user = adminService.getAdminByToken(token);
		String userName = user.getName();
		if(map==null)return AjaxResult.failed("system.parameterError");
		List<Map<String,Object>> datavsList = (List<Map<String,Object>>)map.get("datavslist");
		List<Map<String,Object>> datatestList = (List<Map<String, Object>>)map.get("datatestlist");
		Map<String,Object> header = (Map<String, Object>) map.get("header");

		boolean isSuccess = workSettingService.updateworkorder(userName,header,datavsList,datatestList);
		return AjaxResult.success(isSuccess);

	}
	
	/**
	 * @explain 删除
	 * @param   map 对象参数：id
	 * @return  JsonResult
	 * @author  Wonder
	 */
	@PostMapping("/delete")
	@ApiOperation(value = "删除", notes = "作者：Wonder")
	public AjaxResult<WorkSetting> delete(@RequestBody Map<String,Object> map){
		if(map==null)return AjaxResult.failed("system.parameterError");
		String ids=map.get("id").toString();
		ids=StringUtils.remove(ids, '[');
		ids=StringUtils.remove(ids, ']');
		String[] deleteIds=StringUtils.split(ids, ',');
		List<Long> idList=new ArrayList<>();

		String detailid = map.get("id").toString();

		//删除关联表数据
		workvsService.remove(new QueryWrapper<Workvs>().eq("fdetailid",detailid));
		worktestService.remove(new QueryWrapper<Worktest>().eq("fdetailid",detailid));

		for(int i=0;i<deleteIds.length;i++)
		{
			idList.add( Long.parseLong(deleteIds[i].trim()));//整数数组
		}

	    boolean rsg = workSettingService.removeBatchByIds(idList);
	    if (rsg) {
		    return AjaxResult.success("system.deleteSuccess");
	    }else {
		   return AjaxResult.failed("system.deleteFailed");
	    }
		
	}
	
	/**
	 * @explain 查看对象明细  
	 * @param   map 对象参数：id
	 * @return  JsonResult
	 * @author  Wonder
	 */
	@PostMapping("/detail")
	@ApiOperation(value = "获取工单设置对象明细", notes = "作者：Wonder")
	public AjaxResult<VtuzxMap> detail(@RequestBody Map<String,Object> map){
	    if(map==null) return AjaxResult.failed("system.parameterError");
		Long id=Long.parseLong(map.get("id").toString());		
		VtuzxMap data = workSettingService.getDetail(id);
		if (null!=data ) {
			 return AjaxResult.success(data);
		}else {
			 return AjaxResult.failed("system.parameterError");
		}

	}

	/**
	 * 审核工单
	 * @param request
	 * @param
	 * @return
	 * @throws Exception
	 */
	@PostMapping("/audit")
	@ApiOperation(value = "审核", notes = "作者：Wonder")
	public AjaxResult<WorkSetting> audit(HttpServletRequest request, @RequestBody Map<String,Object> map)throws Exception{
		if (null != map) {
			Long id = Long.parseLong(map.get("id").toString());
			WorkSetting workSetting = workSettingService.getById(id);
			String validate=workSettingService.validate(workSetting,"update");
			if(StringUtils.hasText(validate))
				return AjaxResult.failed(validate);
			//获取token
			String token = checkAdminToken.getTokenFormRequest(request);
			SysAdmin user = adminService.getAdminByToken(token);
			//获取登录名 并赋值
			String userName = user.getName();
			workSetting.setFaudituser(userName);
			workSetting.setFstatus(1);

			//获取当前日期
			Date currentDate = new Date();
			//审核日期
			workSetting.setFauditdate(currentDate);
			workSetting.setFstatus(1);
			boolean rsg = workSettingService.updateById(workSetting);
			if (rsg) {
				//发送mqtt消息
				workSettingService.sendWorkMessage(workSetting);
				return AjaxResult.success("system.updateSuccess");
			}else {
				return AjaxResult.failed("system.updateFailed");
			}
		}else {
			return AjaxResult.failed("system.parameterError");
		}
	}


	/**
	 * 反审核单据
	 * @param request
	 * @param entity
	 * @return
	 * @throws Exception
	 */
	@PostMapping("/unaudit")
	@ApiOperation(value = "反审核", notes = "作者：Wonder")
	public AjaxResult<WorkSetting> unaudit(HttpServletRequest request, @RequestBody WorkSetting entity)throws Exception{
		if (null!=entity) {
			String validate=workSettingService.validate(entity,"update");
			if(StringUtils.hasText(validate))
				return AjaxResult.failed(validate);

			//清空审核人
			entity.setFaudituser("");
			//修改单据状态
			entity.setFstatus(0);
			//清空审核审核日期
			entity.setFauditdate(null);
			boolean rsg = workSettingService.updateById(entity);
			if (rsg) {
				return AjaxResult.success("system.updateSuccess");
			}else {
				return AjaxResult.failed("system.updateFailed");
			}
		}else {
			return AjaxResult.failed("system.parameterError");
		}
	}

	/**
	 * 发送工单信息
	 */
//	private void sendWorkMessage(WorkSetting workSetting){
//		Integer fvcom = workSetting.getFvcom();
//		Integer fvs = workSetting.getFvs();
//		String fbillno = workSetting.getFbillno();//工单号
//		int status = 1;
//		Map<String,Object> data = new HashMap<>();
//
//		if(fvcom == null || fvcom == 0){
//			status += 2;
//
//		}
//		if (fvs == null || fvs == 0){//vs值未录入
//			status += 4;
//		}
//		data.put("FSTATE",status);
//		data.put("FVCOM",fvcom);
//		data.put("FVS",fvs);
//		providerConfig.publish(2,false,"awf_test_info/" + fbillno,data.toString());
//	}
}